package code.rocky.threadlocal;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo05 {

    static ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
    static ExecutorService executorService = Executors.newFixedThreadPool(1);
    static ExecutorService executorService2 = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(1));

    public static void main(String[] args) {
        // 验证TTL 传递性
        threadLocal.set(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getName() + " 线程获取到: " + threadLocal.get());
        Thread t1 = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " 线程获取到: " + threadLocal.get());
        },"t1");
        t1.start();

        InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
        TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();

        // 验证线程池传递
        for (int i = 0; i < 3; i++) {
            inheritableThreadLocal.set("inheritable     -value-> " + i);
            transmittableThreadLocal.set("transmittable -value-> " + i);
            executorService2.submit(() -> {
                System.out.println(transmittableThreadLocal.get());
            });
            executorService.submit(()->{
                System.out.println(inheritableThreadLocal.get());
            });
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            executorService.shutdown();
            executorService2.shutdown();
            inheritableThreadLocal.remove();
            transmittableThreadLocal.remove();
        }
    }
}
